package vn.lumi.smarthome.ui.base;

import com.slidingmenu.lib.app.SlidingFragmentActivity;

import vn.lumi.smarthome.Config;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.service.VibrateThread;
import vn.lumi.smarthome.ui.device.DeviceFragment;
import vn.lumi.smarthome.ui.scene.AddSceneFragmet;
import vn.lumi.smarthome.ui.scene.EditListSceneFragment;
import vn.lumi.smarthome.ui.scene.SceneFragment;
import vn.lumi.smarthome.ulti.Preference;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainFragment extends BaseFragmentMain implements
		View.OnClickListener {
	public static final String TAG = "MainFragment";

	private ViewPager mViewPager;
	// private FixedTabsView mFixedTabsView;

	public static final String FLOOR_ID = "floor_id";
	public static final String ROOM_ID = "room_id";
	public static final String POS = "pos";
	public static final String NAME_ROOM = "nameRoom";
	public static final String NAME_FLOOR = "namefloor";

	// Khai bao bien luu floor_id vs room_id
	protected static String nameRoom;
	protected static String nameFloor;
	private int pos;

	// Cac bien chua thong tin ve loai man hinh
	public static int SCREEN_DEVICE = 0;
	public static int SCREEN_SCENE = 1;
	public static int SCREEN_TOTAL = 2;

	private MainFragmentPagerAdapter mMainFragmentPagerAdapter;
	private static DeviceFragment mDeviceFragment;
	private static SceneFragment mSceneFragment;

	private OnTabSelectedListener mOnTabSelectedListener;

	// Layout actionBar
	LinearLayout layoutActionbar;
	ImageButton acbar_home;
	Button btn_switch, btn_turnAllon, btn_turnAlloff, btn_addScene;

	protected Button btn_editScene;
	protected Boolean isDeviceButton = true; // Kiểm tra trạng thái của button switch
	TextView titleActionbar;
	// private ActionBar actionbar;
	protected boolean isPressableEditScene = true; // Luc dau true de co the bam edit

	/**
	 * @param floor_id
	 * @param room_id
	 * @param pos
	 *            : chi ra fragment nao duoc hien thi
	 * @param isChildFragmentExist
	 *            : fragment child da ton tai hay chua
	 * @return
	 */
	public static MainFragment newInstance(int floor_id, int room_id, int pos,
			String nameRoom, String nameFloor) {
		MainFragment sMainFragment = new MainFragment();
		Bundle bundle = new Bundle();
		bundle.putInt(FLOOR_ID, floor_id);
		bundle.putInt(ROOM_ID, room_id);
		bundle.putInt(POS, pos);
		bundle.putString(NAME_ROOM, nameRoom);
		bundle.putString(NAME_FLOOR, nameFloor);
		sMainFragment.setArguments(bundle);
		return sMainFragment;
	}

	/*
	 * public static MainFragment newInstance(int floor_id, int room_id, int pos) { return
	 * MainFragment.newInstance(floor_id, room_id, pos, nameRoom, nameFloor); }
	 */

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mOnTabSelectedListener = (OnTabSelectedListener) activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mFloor_id = getArguments().getInt(FLOOR_ID);
		mRoom_id = getArguments().getInt(ROOM_ID);
		pos = getArguments().getInt(POS);
		nameFloor = getArguments().getString(NAME_FLOOR);
		nameRoom = getArguments().getString(NAME_ROOM);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		changeLanguage();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_main, container, false);
		init_view(view);
		init_fragment(mFloor_id, mRoom_id);
		return view;
	}

	private void init_view(View view) {
		setupActionBar(view);
		mViewPager = (ViewPager) view
				.findViewById(R.id.fragment_main_viewpager);

		// mMainFragmentPagerAdapter = new MainFragmentPagerAdapter(
		// getFragmentManager());
		mMainFragmentPagerAdapter = new MainFragmentPagerAdapter(
				getChildFragmentManager());
		mViewPager.setAdapter(mMainFragmentPagerAdapter);

		mViewPager.setOnPageChangeListener(mOnPageChangeListener);
		mViewPager.setCurrentItem(pos, true);

		// Neu chuyen sang SceneFragment
		if (pos == MainFragment.SCREEN_SCENE) {
			setButtonToScence();
			isDeviceButton = false;
		}

		// Neu chuyen sang DeviceFragment
		else {
			setButtonToDevice();
			isDeviceButton = true;
		}
	}

	public void setupActionBar(View view) {
		btn_switch = (Button) view.findViewById(R.id.layout_actionbar_switch);
		btn_switch.setOnClickListener(this);
		acbar_home = (ImageButton) view
				.findViewById(R.id.layout_actionbar_home);
		if (MainActivity.isTabletTab()) {
			acbar_home.setVisibility(View.GONE);
		} else {
			acbar_home.setOnClickListener(this);
		}
		btn_turnAlloff = (Button) view
				.findViewById(R.id.layout_actionbar_turnoff);
		btn_turnAlloff.setOnClickListener(this);
		btn_turnAllon = (Button) view
				.findViewById(R.id.layout_actionbar_turnon);
		btn_turnAllon.setOnClickListener(this);
		btn_addScene = (Button) view
				.findViewById(R.id.layout_actionbar_addScence);
		btn_addScene.setOnClickListener(this);
		btn_editScene = (Button) view
				.findViewById(R.id.layout_actionbar_editScence);
		btn_editScene.setOnClickListener(this);
		titleActionbar = (TextView) view
				.findViewById(R.id.layout_actionbar_title);

		setTitleActionbar(nameRoom + "-" + nameFloor);
	}

	private void changeLanguage() {
		Config.configLanguage(getActivity().getBaseContext(),
				Preference.getLanguage(getActivity().getApplicationContext()));// Thiet lap
		// ngon ngu
		btn_turnAllon.setText(R.string.txt_btn_Turn_on);
		btn_turnAlloff.setText(R.string.txt_btn_Turn_off);
	}

	public void setTitleActionbar(String string) {

		/*
		 * Typeface TF = Typeface.createFromAsset(getApplication().getAssets(), LumiHome.font);
		 * getSupportActionBar().setTitleTypeface(TF); getSupportActionBar().setTitle(string);
		 */
		titleActionbar.setText(string);

	}

	public void setButtonToScence() {
		if (Preference.getLanguage(getActivity().getApplicationContext()) == Config.LANGUAGE_VIETNAM) // Neu
			// la
			// ngon
			// ngu
			// Viet
			// Nam
			btn_switch.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.img_switch_canh));
		else if (Preference.getLanguage(getActivity().getApplicationContext()) == Config.LANGUAGE_ENGLISH) { // Neu
			// la
			// ngon
			// ngu
			// English
			btn_switch.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.img_switch_canh_en));
		}
		btn_turnAlloff.setVisibility(View.GONE);
		btn_turnAllon.setVisibility(View.GONE);
		btn_addScene.setVisibility(View.VISIBLE);
		btn_editScene.setVisibility(View.VISIBLE);
		isDeviceButton = false;
	}

	public void setButtonToDevice() {
		if (Preference.getLanguage(getActivity().getApplicationContext()) == Config.LANGUAGE_VIETNAM) // Neu
			// la
			// ngon
			// ngu
			// Viet
			// Nam
			btn_switch.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.img_switch_dev));
		else if (Preference.getLanguage(getActivity().getApplicationContext()) == Config.LANGUAGE_ENGLISH) { // Neu
			// la
			// ngon
			// ngu
			// English
			btn_switch.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.img_switch_dev_en));
		}
		btn_turnAlloff.setVisibility(View.VISIBLE);
		btn_turnAllon.setVisibility(View.VISIBLE);
		btn_addScene.setVisibility(View.GONE);
		btn_editScene.setVisibility(View.GONE);
		isDeviceButton = true;
	}

	public OnPageChangeListener mOnPageChangeListener = new OnPageChangeListener() {

		@Override
		public void onPageSelected(int arg0) {
			if (SCREEN_SCENE == arg0) {
				mOnTabSelectedListener.onTabSelected(TABS.SCENE);
				setButtonToScence();
			} else if (SCREEN_DEVICE == arg0) {
				mOnTabSelectedListener.onTabSelected(TABS.DEVICE);
				setButtonToDevice();
			}
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}
	};

	public void init_fragment(int floor_id, int room_id) {
		mDeviceFragment = DeviceFragment.newInstance(floor_id, room_id,
				nameRoom, nameFloor);
		mSceneFragment = SceneFragment.newInstance(floor_id, room_id, nameRoom,
				nameFloor);
	}

	@Override
	public void refreshData(int floor_id, int room_id, String nameRoom,
			String nameFloor) {
		mFloor_id = floor_id;
		mRoom_id = room_id;
		MainFragment.nameRoom = nameRoom;
		MainFragment.nameFloor = nameFloor;
		mDeviceFragment.refreshData(floor_id, room_id, nameRoom, nameFloor);
		mSceneFragment.refreshData(floor_id, room_id, nameRoom, nameFloor);
		mViewPager.setCurrentItem(SCREEN_DEVICE, true);
		setTitleActionbar(nameRoom + "-" + nameFloor);
	}

	public void onlyRefreshData(int floor_id, int room_id, String nameRoom,
			String nameFloor) {
		mFloor_id = floor_id;
		mRoom_id = room_id;
		MainFragment.nameRoom = nameRoom;
		MainFragment.nameFloor = nameFloor;
		mDeviceFragment.refreshData(floor_id, room_id, nameRoom, nameFloor);
		mSceneFragment.refreshData(floor_id, room_id, nameRoom, nameFloor);
		setTitleActionbar(nameRoom + "-" + nameFloor);
	}

	public void switchFragment(boolean isFragmentDevice) {
		if (isFragmentDevice)
			mViewPager.setCurrentItem(SCREEN_DEVICE, true);
		else
			mViewPager.setCurrentItem(SCREEN_SCENE, true);
	}

	public void turnAllOffOnRoom(int room_id) {
		mDeviceFragment.turnAllOffOnRoom(room_id);
	}

	public void turnAllOnOnRoom(int room_id) {
		mDeviceFragment.turnAllOnOnRoom(room_id);
	}

	private static class MainFragmentPagerAdapter extends FragmentPagerAdapter {
		public MainFragmentPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int arg0) {
			Fragment fragment;
			if (arg0 == SCREEN_SCENE) {
				fragment = mSceneFragment;
			} else {
				fragment = mDeviceFragment;
			}
			return fragment;
		}

		@Override
		public int getCount() {
			return SCREEN_TOTAL;
		}
	}

	public enum TABS {
		SCENE, DEVICE
	}

	public interface OnTabSelectedListener {
		public void onTabSelected(TABS tab);
	}

	public interface ShowMenuListener {
		public void showMenu();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		FragmentManager fragmentManager = getActivity()
				.getSupportFragmentManager();
		FragmentTransaction transaction = fragmentManager.beginTransaction();
		if (Config.isVibrate)
			new VibrateThread(getActivity().getApplicationContext()).start();
		switch (v.getId()) {
		case R.id.layout_actionbar_home:
			((SlidingFragmentActivity) getActivity()).getSlidingMenu()
					.showMenu(true);
			break;
		case R.id.layout_actionbar_switch:
			if (isDeviceButton) {
				setButtonToScence();
				isDeviceButton = false;

				// Bao cho ben ViewPage biet de chuyen sang Fragment canh
				switchFragment(isDeviceButton);

			} else {
				setButtonToDevice();
				isDeviceButton = true;

				// Bao cho ben ViewPage biet de chuyen sang Fragment device
				switchFragment(isDeviceButton);
			}
			// }
			break;
		case R.id.layout_actionbar_turnoff:
			turnAllOffOnRoom(mRoom_id);
			break;
		case R.id.layout_actionbar_turnon:
			turnAllOnOnRoom(mRoom_id);
			break;
		case R.id.layout_actionbar_addScence:
			AddSceneFragmet addSceneFragmet = AddSceneFragmet.newInstance(
					mRoom_id, mFloor_id, nameRoom, nameFloor,
					AddSceneFragmet.TYPE_MAIN_FRAGMENT);

			transaction.replace(R.id.activity_main_content, addSceneFragmet,
					AddSceneFragmet.ADD_SCENE_FRAGMENT);

			// transaction.addToBackStack(null);
			transaction.setCustomAnimations(
					R.animator.fragment_slide_left_enter,
					R.animator.fragment_slide_left_exit,
					R.animator.fragment_slide_right_enter,
					R.animator.fragment_slide_right_exit);

			// Commit the transaction
			transaction.commit();
			break;
		case R.id.layout_actionbar_editScence:
			if (isPressableEditScene) {
				EditListSceneFragment editFragment = (EditListSceneFragment) fragmentManager
						.findFragmentByTag(EditListSceneFragment.EDIT_LIST_SCENE_FRAGMENT);
				if (editFragment == null) {
					editFragment = EditListSceneFragment.newInstance(mFloor_id,
							mRoom_id, nameRoom, nameFloor);
				} else {
					editFragment.refreshData(mFloor_id, mRoom_id, nameRoom,
							nameFloor);
				}

				transaction.replace(R.id.activity_main_content, editFragment,
						EditListSceneFragment.EDIT_LIST_SCENE_FRAGMENT)
						.commit();
				isPressableEditScene = false;
				btn_editScene.setBackgroundResource(R.drawable.img_ok);
			} else {
				setTitleActionbar(nameRoom + "-" + nameFloor);
				MainFragment mainFragment = (MainFragment) fragmentManager
						.findFragmentByTag("main");
				if (mainFragment == null) {
					mainFragment = MainFragment.newInstance(mFloor_id,
							mRoom_id, MainFragment.SCREEN_SCENE, nameRoom,
							nameFloor);
				} else {
					mainFragment.refreshData(mFloor_id, mRoom_id, nameRoom,
							nameFloor);
				}
				transaction.replace(R.id.activity_main_content, mainFragment,
						"main").commit();
				btn_editScene
						.setBackgroundResource(R.drawable.img_editscene_selector);

				isPressableEditScene = true;

			}
			break;
		default:
			break;
		}
	}

}
